//引入扩展组件
Ext.Loader.setConfig({enabled: true});

Ext.Loader.setPath('Ext.ux', '../ExtJS4.2/ux/');

Ext.require([
    'Ext.data.*',
    'Ext.grid.*',
    'Ext.util.*',
    'Ext.tip.QuickTipManager',
    'Ext.ux.data.PagingMemoryProxy',
    'Ext.ux.ProgressBarPager'
]);
var store;
var grid;
var userId;
Ext.onReady(function() {
    var columns = [
                   {xtype: 'rownumberer'},
                   {header:'编号',dataIndex:'user_id',hidden: true},
                   {header:'用户名',dataIndex:'user_name'},
                   {header:'登录名',dataIndex:'login_name'},
                   {header:'登录密码',dataIndex:'login_password',renderer:function(value){
                       return "<span style='color:red;font-weight:bold';>"+value.substring(0,3)+"******</span>";
           			}},
                   {header:'用户状态',dataIndex:'user_status',renderer:function(value){
                       if(value=='DISABLED'){  
                           return "<span style='color:red;font-weight:bold';>禁用</span>";  
                       } else {
                           return "<span style='color:green;font-weight:bold';>正常</span>";  
                       }
           			}},
                   {header:'创建时间',dataIndex:'create_time',renderer:function(value){
                	   return formatDateTime(value);
                   }},
                   {header:'最后更新时间',dataIndex:'update_time',width:150,renderer:function(value){
                	   return formatDateTime(value);
                   }}
               ];
	
    store = Ext.create("Ext.data.Store",{
    	pageSize:15, //每页显示几条数据  
        proxy:{  
            type:'ajax',  
            url:'/user/showUser',  
            reader:{  
                type:'json',
                totalProperty:'total',  
                root:'data',  
                idProperty:'id'  
            }  
        },  
        fields:[  
           {name:'user_id'}, //mapping:0 这样的可以指定列显示的位置，0代表第1列，可以随意设置列显示的位置  
           {name:'user_name'},  
           {name:'login_name'},  
           {name:'login_password'},
           {name:'user_status'},
           {name:'create_time'},
           {name:'update_time'}
        ]  
    });
    
    /*store.on('beforeload', function(loader, node) {
		//var userno = Ext.getCmp('qryUserNo').getValue();
		//var username = Ext.getCmp('qryUserName').getValue();
		//var usertype = Ext.getCmp('qryUserType').getValue();
		//store.baseParams = {userno:userno, username:username, usertype:usertype};
	});*/
    
    var user_dept_store =Ext.create("Ext.data.Store",{
        proxy:{
            type:'ajax',  
            url:'/userdept/findDeptInfoByUserId',
            extraParams:{
                'userId':userId
            },
            reader:{
                type:'json',
                totalProperty:'total',  
                root:'data',  
                idProperty:'dept_id'  
            }
        },
        fields:[  
           {name:'dept_name'},
           {name:'description'}
        ]  
    });
    
    var list_view_dept = Ext.create("Ext.grid.Panel",{
    	id:'listview_dept',
    	title:'用户所属部门信息',
    	autoScroll:true,
    	height:200,
    	border: false,
    	hidden:true,
    	forceFit:true, //自动填满表格  
    	//collapsed:true,
    	//region:'south',
    	loadMask: true,
    	store: user_dept_store,
        columns: [
            {xtype: 'rownumberer'},
            { header: '部门名称',  dataIndex: 'dept_name' },
            { header: '描述', dataIndex: 'description' }
        ],
        renderTo: Ext.getBody()
    });
    
    var sm = Ext.create('Ext.selection.CheckboxModel');
    grid = Ext.create("Ext.grid.Panel",{
    	id:'userGrid',
    	border: false,
    	autoScroll:true,
    	store: store,
    	selModel: sm,
        columns: columns,
        height:520,
        region: 'center', //框架中显示位置，单独运行可去掉此段
        loadMask:true, //显示遮罩和提示功能,即加载Loading……  
        forceFit:true, //自动填满表格  
        columnLines:false, //列的边框
        rowLines:true, //设置为false则取消行的框线样式
        items:[list_view_dept],
        dockedItems: [{
        	xtype:'toolbar',
        	dock:'top',
        	displayInfo: true,
        	items:[
        	       '-',
        	       {
        	    	   xtype:'splitbutton',
        	    	   text: '管理用户',
        	    	   iconCls:'Userhome',
        	    	   menu: Ext.create('Ext.menu.Menu', {
        	    	        items: [
								{id:'addUser',text: '增加用户',iconCls:'Useradd',hidden:true, listeners: {click:function(){addUser();}}},'-',
								{id:'editUser', text: '编辑用户',disabled:true,hidden:true,iconCls:'Useredit',listeners: {click:function(){updateUser();}}},'-',
								{id:'delUser', text: '删除用户',disabled:true,hidden:true,iconCls:'Userdelete',listeners: {click:function(){delUser();}}},'-',
								{id:'crossUser', text: '禁用用户',iconCls:'Usercross',hidden:true,disabled:true,listeners: {click:function(){crossUser();}}},'-',
								{id:'tickUser',text: '启用用户',iconCls:'Usertick',hidden:true,disabled:true,listeners: {click:function(){tickUser();}}},
        	    	        ]
        	    	    })
        	       },
        	       {xtype: 'button', id:'distributionUser', text: '分配部门',iconCls:'Groupadd',disabled:true, hidden:true,listeners: {click:function(){managerDept();}}},
                   {xtype: 'button', id:'importUser',text: '批量导入用户',hidden:true,iconCls:'Databasecopy',
        	    	   listeners: {
        	    		   click:function(){
        	    			   uploadUser();
        	    		   }
        	    	   }},   
        	       {xtype: 'button', id:'exportUser', text: '导出用户',hidden:true,iconCls:'Pageexcel',
        	    	   listeners: {
        	    		   click:function(){
        	    			   exportUserToExcel();
        	    		   }
    	    	   }},
                   {xtype: 'button', id:'print',text: '打印',hidden:true,iconCls:'Printer',
        	    	   listeners: {
        	    		   click:function(){
        	    			   window.print();
        	    		   }
    	    	   }},'->',
    	    	   {id:'searchInput',xtype: 'combo',name: 'name',hidden:true,
    	    		   fieldLabel: '登录名(联想输入，自动检索)',labelAlign:'left',labelWidth:180,
    	    		   store:store, 
    	    		   hideTrigger:true,
    	    		   displayField: 'login_name',
    	               valueField: 'login_name',
    	               queryMode:"local",
    	               editable:true,
    	               triggerAction:"all"
    	           },
                   {id:'searchAll',xtype: 'button', text: '显示全部',hidden:true,iconCls:'Applicationformmagnify',listeners:{click:function(){store.load({params:{start:0,limit:15}}); }}}]
        },{
            xtype: 'pagingtoolbar',
            store: store,   // GridPanel使用相同的数据源
            dock: 'bottom',
            displayInfo: true,
            plugins: Ext.create('Ext.ux.ProgressBarPager'),
            emptyMsg: "没有记录" //没有数据时显示信息
        }]
    });
    //数据排序
    store.sort('create_time','asc');
    //加载数据  
    store.load({params:{start:0,limit:15}}); 
    // 表格配置结束
    
    //监听表格
    grid.getSelectionModel().on({
        selectionchange: function(sm, selections) {
            if (selections.length) {
            	Ext.getCmp('editUser').setDisabled(false);
            	Ext.getCmp('delUser').setDisabled(false);
            	Ext.getCmp('crossUser').setDisabled(false);
            	Ext.getCmp('tickUser').setDisabled(false);
            	Ext.getCmp('distributionUser').setDisabled(false);
            } else {
            	Ext.getCmp('editUser').setDisabled(true);
            	Ext.getCmp('delUser').setDisabled(true);
            	Ext.getCmp('crossUser').setDisabled(true);
            	Ext.getCmp('tickUser').setDisabled(true);
            	Ext.getCmp('distributionUser').setDisabled(true);
            }
        }
    });
    
    //表格右键菜单  
    var contextmenu = new Ext.menu.Menu({  
        id:'theContextMenu',  
        items:[{
        	id:'rightAddUser',
            text:'增加用户',
            hidden:true,
            iconCls:'Useradd',
            handler:function(){  
            	addUser();  
            }  
        },{
        	id:'rightEditUser',
            text:'编辑用户',
            hidden:true,
            iconCls:'Useredit',
            handler:function(){  
            	updateUser();
            }  
        },{
        	id:'rightDelUser',
            text:'删除用户',
            hidden:true,
            iconCls:'Userdelete',
            handler:function(){  
            	delUser();
            }  
        },{
        	id:'rightDistributionUser',
            text:'分配部门',
            hidden:true,
            iconCls:'Groupadd',
            handler:function(){  
            	managerDept();
            }
        },{
        	id:'rightCrossUser',
            text:'禁用用户',
            hidden:true,
            iconCls:'Usercross',
            handler:function(){  
            	crossUser();
            }  
        },{
        	id:'rightTickUser',
        	text:'启用用户',
        	hidden:true,
        	iconCls:'Usertick',
        	handler:function(){  
        		tickUser();
            }  
        },{
        	id:'rightImportUser',
            text:'批量导入用户',
            hidden:true,
            iconCls:'Databasecopy',
            handler:function(){  
            	uploadUser();
            }  
        },{
        	id:'rightExportUser',
            text:'导出用户',
            hidden:true,
            iconCls:'Pageexcel',
            handler:function(){  
            	exportUserToExcel();
            } 
        },{
        	id:'rightPrint',
            text:'打印',
            hidden:true,
            iconCls:'Printer',
            handler:function(){  
            	window.print();
            }  
        },{
        	id:'rightRefresh',
			text : '刷新',
			hidden:true,
			iconCls: "Arrowrefreshsmall",
			handler : function(){
				store.reload();
			}  
		}]  
    });  
    
    grid.on("itemcontextmenu",function(view,record,item,index,e){  
        e.preventDefault();  
        contextmenu.showAt(e.getXY());  
    });
    
    grid.on("itemdblclick",function(grid, row){
    	updateUser(); 
    });
    
    grid.on('itemclick', function(grid, rowIndex, e) {
		var rec = grid.getSelectionModel().getLastSelected();
		/*store_user_agent.removeAll();
		store_user_agent.proxy.setUrl(window.webRoot + 'rest/user/' + rec.get('id') + '/agents', true);
		store_user_agent.load();
		store_user_role.proxy.setUrl(window.webRoot + 'rest/user/' + rec.get('id') + '/roles', true);
		store_user_role.load();*/
		//设置面板出现
		Ext.getCmp('listview_dept').setVisible(true);
		Ext.getCmp('userGrid').setHeight(300);
		userId = rec.get('user_id');
		//Ext.getCmp('listview_dept').setHeight('20%');
    	//用户-部门信息
		//user_dept_store.removeAll();
        user_dept_store.load({params:{userId:userId}}); 
	});
    
    //亮点功能
    //判断页面按钮是否有权限
    //默认全部禁用，取出数据对比，如果分配了则显示使用，否则禁用
    grid.on("afterRender",function(){
    	Ext.Ajax.request({
            url: '/menuPer/getMenuPer',
            timeout: 30000,
          	success: function(response,options) {
          		var respText = Ext.JSON.decode(response.responseText);
          		if(respText.code == 'OK') {
          			var rec = respText.data;
          			for(var i=0; i<rec.length; i++){
          				if(rec[i].kind=='addUser'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('addUser').hidden=true;
          					}else{
          						Ext.getCmp('addUser').hidden=false;
          					}
          				}
          				if(rec[i].kind=='editUser'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('editUser').hidden=true;
          					}else{
          						Ext.getCmp('editUser').hidden=false;
          					}
          				}
          				if(rec[i].kind=='delUser'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('delUser').hidden=true;
          					}else{
          						Ext.getCmp('delUser').hidden=false;
          					}
          				}
          				if(rec[i].kind=='crossUser'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('crossUser').hidden=true;
          					}else{
          						Ext.getCmp('crossUser').hidden=false;
          					}
          				}
          				if(rec[i].kind=='tickUser'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('tickUser').hidden=true;
          					}else{
          						Ext.getCmp('tickUser').hidden=false;
          					}
          				}
          				if(rec[i].kind=='distributionUser'){
          					var addUserV = rec[i].value;
          					//按钮不能使用.hidden=true;
          					if(addUserV =='true'){
          						Ext.getCmp('distributionUser').hide();
          					}else{
          						Ext.getCmp('distributionUser').show();
          					}
          				}
          				if(rec[i].kind=='importUser'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('importUser').hide();
          					}else{
          						Ext.getCmp('importUser').show();
          					}
          				}
          				if(rec[i].kind=='exportUser'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('exportUser').hide();
          					}else{
          						Ext.getCmp('exportUser').show();
          					}
          				}
          				if(rec[i].kind=='print'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('print').hide();
          					}else{
          						Ext.getCmp('print').show();
          					}
          				}
          				if(rec[i].kind=='searchInput'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('searchInput').hide();
          					}else{
          						Ext.getCmp('searchInput').show();
          					}
          				}
          				if(rec[i].kind=='searchAll'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('searchAll').hide();
          					}else{
          						Ext.getCmp('searchAll').show();
          					}
          				}
          				if(rec[i].kind=='rightAddUser'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('rightAddUser').hidden=true;
          					}else{
          						Ext.getCmp('rightAddUser').hidden=false;
          					}
          				}
          				if(rec[i].kind=='rightEditUser'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('rightEditUser').hidden=true;
          					}else{
          						Ext.getCmp('rightEditUser').hidden=false;
          					}
          				}
          				if(rec[i].kind=='rightDelUser'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('rightDelUser').hidden=true;
          					}else{
          						Ext.getCmp('rightDelUser').hidden=false;
          					}
          				}
          				if(rec[i].kind=='rightDistributionUser'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('rightDistributionUser').hidden=true;
          					}else{
          						Ext.getCmp('rightDistributionUser').hidden=false;
          					}
          				}
          				if(rec[i].kind=='rightCrossUser'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('rightCrossUser').hidden=true;
          					}else{
          						Ext.getCmp('rightCrossUser').hidden=false;
          					}
          				}
          				if(rec[i].kind=='rightTickUser'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('rightTickUser').hidden=true;
          					}else{
          						Ext.getCmp('rightTickUser').hidden=false;
          					}
          				}
          				if(rec[i].kind=='rightImportUser'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('rightImportUser').hidden=true;
          					}else{
          						Ext.getCmp('rightImportUser').hidden=false;
          					}
          				}
          				if(rec[i].kind=='rightExportUser'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('rightExportUser').hidden=true;
          					}else{
          						Ext.getCmp('rightExportUser').hidden=false;
          					}
          				}
          				if(rec[i].kind=='rightPrint'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('rightPrint').hidden=true;
          					}else{
          						Ext.getCmp('rightPrint').hidden=false;
          					}
          				}
          				if(rec[i].kind=='rightRefresh'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('rightRefresh').hidden=true;
          					}else{
          						Ext.getCmp('rightRefresh').hidden=false;
          					}
          				}
          			}
          		}
          	},
          	failure: function(response,options) {}
          });
    });
    
    
    var centerPanel = Ext.create("Ext.panel.Panel", {
        region: 'center',
        type:'vbox',
        defaults: {
            autoScroll: true,
          //  autoHeight: true
        },
        items: [grid,list_view_dept]
    });
    
	// 整体架构容器
	Ext.create("Ext.container.Viewport", {
		layout : 'border',
		autoHeight: true,
		border: false,
		items : [centerPanel]
	});
});